<?php
/*
 * @Author: lokei
 * @Date: 2022-09-24 00:41:40
 * @LastEditors: lokei
 * @LastEditTime: 2022-11-19 09:23:12
 * @Description: 
 */

namespace App\Http\Controllers\Ucenter\Mobile;

use App\Common\Miniapp\Common;
use App\Common\Tools\ResultTool;
use GuzzleHttp;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

use Alipay\EasySDK\Kernel\Factory;
use App\Common\Alipay\Common as AliCommon;
use App\Models\Platform\Conf\ConfAlipayModel;
use App\Models\Ucenter\UserModel;

class MobileController extends Controller
{
    public function getWxBind(Request $request)
    {
        $access_token = Common::getAccessToken();
        $http = new GuzzleHttp\Client;
        $params = [
            'code' => $request->input('code')
        ];
        $response = $http->post('https://api.weixin.qq.com/wxa/business/getuserphonenumber', [
            'query' => [
                'access_token' => $access_token,
                'code' => $request->input('code')
            ],
            'json' => $params
        ]);
        $result = json_decode($response->getBody(), true);
        if ($result['errcode'] == 0) {
            $res = ResultTool::success();
            $res['data'] = $result['phone_info'];
            return $res;
        }
        return ResultTool::fail();
    }

    public function getAliBind(Request $request)
    {
        $conf = ConfAlipayModel::first();
        $options = AliCommon::getOptions();
        $options->encryptKey = $conf->secret_key;

        Factory::setOptions($options);

        $response = json_decode($request->input('response'));
        $content = $response->response;
        $result_str = Factory::util()->aes()->decrypt($content);
        $result = json_decode($result_str);

        if ($result->code == 10000) {
            $res = ResultTool::success();
            $res['data']['mobile'] = $result->mobile;
            return $res;
        } else {
            $res = ResultTool::fail();
            $res['errorCode'] = $result->code;
            $res['errorMsg'] = $result->msg;
            return $res;
        }
    }

    public function updateOfMe(Request $request)
    {
        $user = app('auth')->user();
        $is_other = UserModel::where('mobile', '=', $request->input('mobile'))->where('uid', '!=', $user->uid)->first();
        if (!is_null($is_other)) {
            $res = ResultTool::fail();
            $res['errorCode'] = 201;
            $res['errorMsg'] = '手机号已经绑定其它用户！';
            return $res;
        } else {
            $user->mobile = $request->input('mobile');
            $user->save();
            return ResultTool::success();
        }
    }
}
